package com.isunland.managesystem.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;

/**
 * 查看或下载附件.
 *
 * @author wangyanan
 */
public class ExtraDownLoadDialogFragment extends DialogFragment {
  private static final String EXTRA_FILE_LOCAL = "com.isunland.managesystem.ui.EXTRA_FILE_LOCAL";
  private static final String EXTRA_FILE_SERVER = "com.isunland.managesystem.ui.EXTRA_FILE_SERVER";
  private static final int REQUEST_CODE_ASK_PERMISSIONS = 2;
  /** 服务器上Android路径 */
  private static String mFilePathLocal = "";
  private static String mFilePathServer = "";
  /** 显示下载还是查看,0下载,1查看 */
  private int mType;
  private File mFile;
  private static int VALUE_DOWNLOAD = 0;
  private static int VALUE_SHOW = 1;
  /** 根据服务器上路径获取的文件名 */
  private String mFileName;
  private AlertDialog mDialog;
  private BaseVolleyActivity mActivity;

  @Override public void onCreate(Bundle savedInstanceState) {
    mFilePathLocal = getArguments().getString(EXTRA_FILE_LOCAL);
    mFilePathServer = getArguments().getString(EXTRA_FILE_SERVER);
    mFileName = FileUtil.getFileNameByFilePath(mFilePathServer);
    mType = initType();
    mActivity = (BaseVolleyActivity) getActivity();
    super.onCreate(savedInstanceState);
  }

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    //		if (Build.VERSION.SDK_INT >= 23) {
    //			int checkNetPermission = ContextCompat.checkSelfPermission(getActivity(),
    //					Manifest.permission.READ_EXTERNAL_STORAGE);
    //			int checkGpsPermission = ContextCompat.checkSelfPermission(getActivity(),
    //					Manifest.permission.WRITE_EXTERNAL_STORAGE);
    //
    //			if (checkNetPermission != PackageManager.PERMISSION_GRANTED
    //					&& checkGpsPermission != PackageManager.PERMISSION_GRANTED) {
    //				ActivityCompat.requestPermissions(getActivity(),
    //						new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE }, REQUEST_CODE_ASK_PERMISSIONS);
    //			}
    //		}
    if (VALUE_DOWNLOAD == mType) {
      mDialog = createDownLoadDialog();
    } else {
      mDialog = createShowDialog();
    }

    return mDialog;
  }

  private AlertDialog createDownLoadDialog() {

    final AlertDialog dialogDownLoad =
        new AlertDialog.Builder(getActivity()).setTitle(R.string.hintMessage)
            .setMessage(MyStringUtil.connect(getString(R.string.haveNotDownload), "\n", mFileName))
            .setPositiveButton(R.string.download, null)
            .setNeutralButton(android.R.string.cancel, null)
            .create();
    dialogDownLoad.setOnShowListener(new OnShowListener() {

      @Override public void onShow(final DialogInterface dialog) {
        Button positiveButton = dialogDownLoad.getButton(AlertDialog.BUTTON_POSITIVE);
        Button neutralButton = dialogDownLoad.getButton(AlertDialog.BUTTON_NEUTRAL);

        positiveButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {
            new FileNetWorkUtil(getActivity()).downLoadFile(mFilePathServer, mFileName, null);

            dialogDownLoad.dismiss();
          }
        });
        neutralButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {

            dialog.dismiss();
          }
        });
      }
    });

    return dialogDownLoad;
  }

  private AlertDialog createShowDialog() {

    final AlertDialog dialogShow =
        new AlertDialog.Builder(getActivity()).setTitle(R.string.hintMessage)
            .setMessage(MyStringUtil.connect(getString(R.string.alreadyDownload), "\n", mFileName))
            .setPositiveButton(R.string.show, null)
            .setNeutralButton(R.string.delete, null)
            .setNegativeButton(android.R.string.cancel, null)
            .create();
    dialogShow.setOnShowListener(new OnShowListener() {

      @Override public void onShow(final DialogInterface dialog) {
        Button positiveButton = dialogShow.getButton(AlertDialog.BUTTON_POSITIVE);
        Button negtiveButon = dialogShow.getButton(AlertDialog.BUTTON_NEGATIVE);
        Button deleteButton = dialogShow.getButton(AlertDialog.BUTTON_NEUTRAL);
        deleteButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {

            boolean isDelete = FileUtil.deleteFile(new File(mFilePathLocal));
            int hintId = isDelete ? R.string.deleteSuccess : R.string.deleteFail;
            ToastUtil.show(hintId);
            dialogShow.dismiss();
          }
        });
        positiveButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {

            FileUtil.openFile(new File(mFilePathLocal), getActivity());
            dialogShow.dismiss();
          }
        });
        negtiveButon.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {

            dialog.dismiss();
          }
        });
      }
    });

    return dialogShow;
  }

  private int initType() {
    // 服务器android路径上寻找.
    if (!TextUtils.isEmpty(mFilePathLocal)) {
      mFile = new File(mFilePathLocal);
      if (mFile.exists()) {
        return VALUE_SHOW;
      }
    }
    //本地Android文件路径上寻找.
    if (mFileName == null) {
      mFileName = "";
    }
    mFile = new File(FileUtil.getFileDir(), mFileName);

    if (!mFile.getParentFile().exists()) {

      mFile.getParentFile().mkdirs();
    }
    if (!mFile.exists()) {

      return VALUE_DOWNLOAD;
    } else {
      mFilePathLocal = mFile.getAbsolutePath();
      return VALUE_SHOW;
    }
  }

  public static ExtraDownLoadDialogFragment newInstance(String filePathLocal,
      String filePathServer) {
    Bundle argsBundle = new Bundle();

    argsBundle.putString(EXTRA_FILE_LOCAL, filePathLocal);
    argsBundle.putString(EXTRA_FILE_SERVER, filePathServer);
    ExtraDownLoadDialogFragment fragment = new ExtraDownLoadDialogFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }
}
